package com.sicheng.algorithm.node;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/9/18 15:36
 */
public class FindFirstCommonNode {

    public static void main(String[] args) {

        ListNode head1 = ListNode.initList(new int[]{1, 2});
        ListNode head2 = ListNode.initList(new int[]{4, 5, 6});
        ListNode head3 = ListNode.initList(new int[]{101, 102, 103, 104});

        ListNode tail1 = ListNode.getTail(head1);
        ListNode tail2 = ListNode.getTail(head2);

        tail1.next = head3;
        tail2.next = head3;

        System.out.println(findFirstCommonNode(head1, head2));
    }

    public static ListNode findFirstCommonNode(ListNode head1, ListNode head2) {

        if (head1 == null || head2 == null)
            return null;
        ListNode temp1 = head1, temp2 = head2;

        while (temp1 != temp2) {
            temp1 = temp1 == null ? head2 : temp1.next;
            temp2 = temp2 == null ? head1 : temp2.next;
        }

        return temp1;
    }


}
